<template>
	<div class="app-container">
		<div>
      <p class="dialogTitle title">当前地震事件:
        <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
        <span v-else>请在地震事件管理中设置当前地震事件</span>
      </p>
    </div>
    <el-row>
			<el-col :span="8">
				<div style="font-size: 16px;font-weight: bold;">1、通过调查数据计算房屋直接经济损失</div>
			</el-col>
		</el-row>	
		<el-row style="margin-top: 20px;">
			<el-col :span="8">
				<div style="font-size: 16px;font-weight: bold;">&nbsp;&nbsp;1）评估子区各类房屋不同破坏状态下的房屋直接经济损失</div>
			</el-col>
			<el-col :span="6">
				<el-link type="primary" :underline="false" @click="viewFormula">查看计算公式</el-link>
			</el-col>
		</el-row>
		<el-row style="margin-top: 20px;">
			<el-col :span="6">
				<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
					<el-form-item label="评估子区" prop="xstmId">
						<el-select v-model="queryParams.xstmId" placeholder="请选择评估子区" @change="changeXstmId" clearable>
              <el-option v-for="item in option" :key="item.xstmId" :label="item.evaluationSubareaName" :value="item.xstmId">
              </el-option>
            </el-select>
					</el-form-item>
				</el-form>
			</el-col>
			<el-col :span="6">
				<el-button type="primary" @click="handleQuery">计算</el-button>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="18">
				<el-table v-loading="loading" :data="dataList"  :span-method="objectSpanMethod" border>
					<el-table-column label="评估子区" align="center" prop="evaluationSubareaName" />
					<el-table-column label="结构类型" align="center" prop="structureType" >
						<template #default="scope">					
		          {{getStructureType(scope.row.structureType)}}
		        </template>
		      </el-table-column>
					<el-table-column label="基本完好" align="center" prop="intactValue" />
					<el-table-column label="轻微破坏" align="center" prop="minorValue" />
					<el-table-column label="中等破坏" align="center" prop="moderateValue" />
					<el-table-column label="严重破坏" align="center" prop="seriousValue" />
					<el-table-column label="毁坏" align="center" prop="destroyValue" />
					<el-table-column label="房屋损失（万元）" align="center" prop="totalLoss" />
				</el-table>
				<pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getListA" />
			</el-col>
		</el-row>
		<el-row style="margin-top: 20px;margin-bottom: 20px;">
			<el-col :span="6">
				<div style="font-size: 16px;font-weight: bold;">&nbsp;&nbsp;2）评估子区和灾区房屋直接经济损失</div>
			</el-col>
			<el-col :span="6">
				<el-button type="primary" @click="handleQuery1">计算</el-button>
			</el-col>
		</el-row>
		
		<el-row>
			<el-col :span="18">
				<el-table v-loading="loading1" :data="dataList1" stripe>
					<el-table-column label="评估子区名称" align="center" prop="evaluationSubareaName" />
					
					<el-table-column label="房屋损失（万元）" align="center" prop="housesLosses" />
				</el-table>
			</el-col>
		</el-row>
		<el-row style="margin-top: 20px;margin-bottom: 20px;">
			<el-col :span="6">
				<div style="font-size: 16px;font-weight: bold;">&nbsp;&nbsp;3） 按行政区划汇总不同用途下的房屋直接经济损失</div>
			</el-col>
			<el-col :span="6">
				<el-button type="primary" @click="summary">汇总</el-button>
			</el-col>
		</el-row>
		
		<el-row>
			<el-col :span="18">
				<el-table v-loading="loading2" :data="dataList2" stripe>
					<el-table-column label="行政区划（省市县）" align="center" prop="" >
						<template #default="scope">
							<span v-if="scope.row.province=='北京市'||scope.row.province=='天津市'||scope.row.province=='上海市'||scope.row.province=='重庆市'">{{scope.row.province}}{{scope.row.county}}</span>
              <span v-else>{{scope.row.province}}{{scope.row.city}}{{scope.row.county}}</span>
            </template>
					</el-table-column>
					<el-table-column label="房屋直接经济损失(万元)" align="center" prop="housesLosses" >
						<el-table-column label="农村住宅" align="center" prop="ruralHouse" />
						<el-table-column label="农村共用" align="center" prop="ruralShared" />
						<el-table-column label="城市住宅" align="center" prop="cityHouse" />
						<el-table-column label="城市公用" align="center" prop="cityShared" />
						<el-table-column label="政府办公" align="center" prop="governmentOffice" />
						<el-table-column label="教育系统" align="center" prop="educationSystem" />
						<el-table-column label="卫生系统" align="center" prop="healthSystem" />
						<el-table-column label="其他用途" align="center" prop="otherUsage" />
					</el-table-column>
				</el-table>
			</el-col>
		</el-row>
		<el-dialog title="计算公式" v-model="open" width="700px" append-to-body>
			<div style="font-size: 16px;">
				<p>房屋破坏直接经济损失，应按下列步骤计算：</p>
				<p>&nbsp;a) 按式(1)计算各评估子区各类房屋在某种破坏等级下的损失L</p>
				    <p>&nbsp;&nbsp;&nbsp;&nbsp;Lh=Sh×Rh×Dh×Ph    .............................(1)</p>
				  <p>&nbsp;&nbsp;&nbsp;式中：</p>
				   <p>&nbsp;&nbsp;&nbsp;Sh——该评估子区同类房屋总建筑面积，单位为平方米；</p>
				   <p>&nbsp;&nbsp;&nbsp;Rh——该评估子区同类房屋某种破坏等级的破坏比；</p>
				   <p>&nbsp;&nbsp;&nbsp;Dh——该评估子区同类房屋某种破坏等级的损失比；</p>
				   <p>&nbsp;&nbsp;&nbsp;Ph——该评估子区同类房屋重置单价，单位为元每平方米。</p>
				<p>&nbsp;b) 将所有破坏等级的房屋损失相加，得到该评估子区该类房屋破坏的损失；</p>
				<p>&nbsp;c) 将所有类别房屋的损失相加，得到该评估子区房屋损失；</p>
				<p>&nbsp;d) 将所有评估子区的房屋损失相加，得出整个灾区的房屋损失。</p>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="open = false">关 闭</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="DirectEconomic">
	import useEventStore from "@/store/modules/event";
	import { getAllList,getListAll,getFailureRatioByXsemId, getAllList1, getEvaluationSubArea, getDisasterAreasHousesData, getAreaHousesDirectEconomicLosses, getAdministrationData } from "@/api/directLossAssess/directEconomic.js"
	import { getDict } from "@/api/system/dict";
	import { ElMessageBox, ElMessage } from 'element-plus'
	const {
		proxy
	} = getCurrentInstance();
	const dataList = ref([]);
	const dataList1 = ref([]);
	const dataList2 = ref([]);
	const ids = ref();
	const loading = ref(false);
	const loading1 = ref(false);
	const loading2 = ref(false);
	const single = ref(true);
	const multiple = ref(true);
	const open = ref(false);
	const total = ref(0);
	const showSearch = ref(true);
	const currentEvent = computed(() => useEventStore().currentEvent);
	const option = ref([]);
	const option1 = ref([]);
	const data = reactive({
		queryParams: {
			page: 1,
			rows: 10,
			xstmId: undefined,
			evaluationSubareaName: "",			
		},
		form: {}
	})
	const {
		queryParams,
		form
	} = toRefs(data)

	function changeXstmId(){
		getListA();
	}

	// 计算
	function handleQuery() {
		queryParams.value.page = 1;
		// if(!queryParams.value.xstmId){
		// 	proxy.$modal.msgWarning("请选择评估子区");
		// 	return
		// }
		option.value.forEach(item => {
      if (item.xstmId == queryParams.value.xstmId) {
        queryParams.value.evaluationSubareaName = item.evaluationSubareaName;
      }
  	})
	  getFailureRatioByXsemId({xsemId:currentEvent.value.id}).then(res=>{
			if(res.data.length!=0){
				ElMessageBox.confirm("重复计算提示“已经有计算结果，重新计算会覆盖上次的计算结果，是否继续计算?", "系统提示", 
					{
						cancelButtonText: '取消',
						confirmButtonText: '确定',
						dangerouslyUseHTMLString: true,
          	type: "warning",
					}).then(() => {
						getList();
				}).catch(() => {});
			}else{
				getList();
			}
		})
	}
	function handleQuery1() {
		getList1();
	}
	
	function summary() {
		getList2();
	}

	/** 重置按钮操作 */
	function resetQuery() {
		dataList.value = [];
		proxy.resetForm("queryRef");
		handleQuery();
	}

	/** 导出按钮操作 */
	function handleExport() {
		proxy.downloadTemplate('/samPoiData/exportExcel', {
			xsemId: currentEvent.value.id
		}, `抽样点数据${new Date().getTime()}.xls`)
	}

	// 编辑
	function handleEdit(row) {
		detail(row.id);
	}

	// 查看计算公式
	function viewFormula(id) {
		open.value = true;
	}
	
	function getEvaluationSubAreaList() {
		getEvaluationSubArea(currentEvent.value?.id).then(response => {
			if(response.data.list.length>0){
				option.value = response.data.list
			}else{
				ElMessage({
					message: response.data.message,
					type: 'warning',
					dangerouslyUseHTMLString: true
				})
			}
		});
	}
	function getDisasterAreasHousesDataList(){
		getDisasterAreasHousesData({xsemId:currentEvent.value?.id}).then(response => {
			dataList1.value = response.data ? response.data : [];
		});
	}
	
	function getAreaHouses(){
		getAdministrationData(currentEvent.value?.id).then(response => {
			dataList2.value = response.data ? response.data : [];
		});
	}

	/** 查询数据列表 */
	function getListA() {
			loading.value = true;
			getListAll({...queryParams.value,xsemId:currentEvent.value?.id}).then(response => {
				dataList.value = response.data.rows ? response.data.rows : [];
				total.value = response.data.total;
				loading.value = false;
			}).catch(() => loading.value = false);
	}

	/** 查询数据列表 */
	function getList() {
			loading.value = true;
			getAllList({...queryParams.value,xsemId:currentEvent.value.id}).then(response => {
				// proxy.$modal.msgSuccess(response.message);
				getListA();
				loading.value = false;
			}).catch(() => loading.value = false);
	}
		/** 查询数据列表 */
	function getList1() {
			loading1.value = true;
			getAllList1({xsemId:currentEvent.value.id}).then(response => {
				dataList1.value = response.data ? response.data : [];
				//total.value = response.data.total;
				loading1.value = false;
				// proxy.$modal.msgSuccess(response.message);
			}).catch(() => loading1.value = false);
	}
	function getList2() {
			loading2.value = true;
			getAreaHousesDirectEconomicLosses({xsemId:currentEvent.value.id}).then(response => {
				getAreaHouses();
				// dataList2.value = response.data ? response.data : [];
				//total.value = response.data.total;
				loading2.value = false;
				// proxy.$modal.msgSuccess(response.message);
			}).catch(() => loading2.value = false);
	}
	function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
	 if (columnIndex === 0) {
		 const _row = setTable(dataList.value).one[rowIndex];
		 const _col = _row > 0 ? 1 : 0;
		 return {
			 rowspan: _row,
			 colspan: _col
		 };
	 }
//	 if (columnIndex === 1 ) {
//		 const _row = setTable(getData.value).two[rowIndex];
//		 const _col = _row > 0 ? 1 : 0;
//		 return {
//		 rowspan: _row,
//			 colspan: _col
//			};
//		}
//	 if (columnIndex === 3 ) {
//		 const _row = setTable(getData.value).three[rowIndex];
//		 const _col = _row > 0 ? 1 : 0;
//		 return {
//		 rowspan: _row,
//			 colspan: _col
//			};
//		}
//	 if (columnIndex === 4 ) {
//		 const _row = setTable(getData.value).four[rowIndex];
//		 const _col = _row > 0 ? 1 : 0;
//		 return {
//		 rowspan: _row,
//			 colspan: _col
//			};
//		}
}
	function setTable(tableData) {
		 let spanOneArr = [],
		 spanTwoArr = [],
		 spanThreeArr = [],
		 spanFourArr = [],
		 concatOne = 0,
		 concatTwo = 0,
		 concatThree = 0,
		 concatFour = 0;
		 tableData.forEach((item, index) => {
			 if (index === 0) {
				 spanOneArr.push(1);
				 spanTwoArr.push(1);
				 spanThreeArr.push(1);
				 spanFourArr.push(1);
			 } else {
				 if (item.evaluationSubareaName === tableData[index - 1].evaluationSubareaName) {
				 //第一列需合并相同内容的判断条件
					 spanOneArr[concatOne] += 1;
					 spanOneArr.push(0);
				 } else {
					 spanOneArr.push(1);
					 concatOne = index;
				 }
				 
	//			 if (item.longitude === tableData[index - 1].longitude) {
	//			 //第二列和需合并相同内容的判断条件
	//				 spanTwoArr[concatTwo] += 1;
	//				 spanTwoArr.push(0);
	//			 } else {
	//				 spanTwoArr.push(1);
	//				 concatTwo = index;
	//			 }
	//			 
	//			 if (item.latitude === tableData[index - 1].latitude) {
	//			 //第三列和需合并相同内容的判断条件
	//				 spanThreeArr[concatThree] += 1;
	//				 spanThreeArr.push(0);
	//			 } else {
	//				 spanThreeArr.push(1);
	//				 concatThree = index;
	//			 }
	//			 
	//			 if (item.macroPosition === tableData[index - 1].macroPosition) {
	//			 //第三列和需合并相同内容的判断条件
	//				 spanFourArr[concatFour] += 1;
	//				 spanFourArr.push(0);
	//			 } else {
	//				 spanFourArr.push(1);
	//				 concatFour = index;
	//			 }
			 }
		 });
	 	return {
			 one: spanOneArr,
			 two: spanTwoArr,
			 three: spanThreeArr,
			 four: spanFourArr,
	 	};
	}
	/** 获取字典值 */
	async function getDictData() {
		await getDict("jglx").then(response => {
		    option1.value = response.data;
		});
	}
	function getStructureType(val){
	  var name = ''
	  option1.value.forEach(item => {
			if(item.dictItemCode == val) {
				name = item.dictItemName
				return
			}
		})
		return name
	}
	onMounted(() => {
		setTimeout(() => {
			getEvaluationSubAreaList();
			getDisasterAreasHousesDataList();
			getAreaHouses();
			getListA();
			//getList();
		}, 200)
	})
	getDictData();
</script>

<style scoped lang="scss">
	.title {
		margin: 0 0 20px !important;
	}
	:deep(.el-table) th.el-table__cell {
    border-bottom: 1px solid #ffffff !important;
    border-right: 1px solid #ffffff !important;
	}
	:deep(.el-table) td.el-table__cell {
    border-bottom: 1px solid #ebeef5 !important;
    border-right: 1px solid #ebeef5 !important;
	}
</style>